package archive

import (
	"archive/zip"
	"io"
)

var Zip = &archiveZip{}

type archiveZip struct{}

func (receiver *archiveZip) Writer(writer io.Writer, files []File) error {
	zipWriter := zip.NewWriter(writer)

	// tarWriter.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
	// 	return flate.NewWriter(out, flate.BestCompression)
	// })

	for _, file := range files {
		ioWriter, err := zipWriter.Create(file.Name)
		if err != nil {
			return err
		}

		_, err = ioWriter.Write([]byte(file.Body))
		if err != nil {
			return err
		}
	}

	if err := zipWriter.Close(); err != nil {
		return err
	}

	return nil
}
func (receiver *archiveZip) Reader(reader io.Reader) ([]File, error) {
	zipReader, err := zip.OpenReader("readme.zip")
	// zipReader, err := zip.OpenRaw(reader)
	// zipReader, err := zip.NewReader(reader)
	if err != nil {
		return nil, err
	}
	defer zipReader.Close()

	var files []File

	for _, zipFile := range zipReader.File {
		fileCloser, err := zipFile.Open()
		if err != nil {
			return nil, err
		}
		defer fileCloser.Close()

		var body []byte
		length, err := fileCloser.Read(body)
		if err != nil {
			return nil, err
		}

		var file File
		file.Name = zipFile.Name
		file.Body = zipFile.Name
		file.Length = length

		files = append(files, file)
	}

	return nil, nil
}
